package com.cloudbroker.bcs.platform.ltb.common.ext.messageconverter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.ReflectionUtil;
import com.cloudbroker.bcs.platform.ltb.common.constant.IFSField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dengwei06015 on 2016/1/19.
 */
public class MyFastJsonHttpMessageConverter extends FastJsonHttpMessageConverter {
    private static Logger log = LoggerFactory.getLogger(MyFastJsonHttpMessageConverter.class);

    protected void writeInternal(Object obj, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
        if(obj instanceof Map){
            Map<String, Object> jsonp = (Map) obj;
            String jsonpcallback = (String) jsonp.remove(IFSField.JSONPCALLBACK);
            disposeWithJsonp(jsonpcallback ,outputMessage, jsonp);
        }else if(obj instanceof HSBCPSBackVO) {
            HSBCPSBackVO backVO = (HSBCPSBackVO) obj;
            ReflectionUtil.hiddenEmptyAttrToJson(obj);
            Map<String,Object> result = new HashMap<>();
            result.put(IFSField.DATA, new HSBCPSBackVO[]{ backVO });
            disposeWithJsonp(backVO.getJsonpcallback() ,outputMessage, result);
        } else{
            writeInternalWithGson(obj, outputMessage);
        }
    }

    private void disposeWithJsonp(String jsonpcallback,HttpOutputMessage outputMessage, Map<String, Object> result) throws IOException {
        if (jsonpcallback != null) {
            OutputStream out = outputMessage.getBody();
            String text = jsonpcallback + "(" + JSON.toJSONString(result, this.getFeatures()) + ")";
            byte[] bytes = text.getBytes(getCharset());
            out.write(bytes);
        } else {
            writeInternalWithGson(result, outputMessage);
        }
    }

    protected void writeInternalWithGson(Object obj, HttpOutputMessage outputMessage) throws IOException,
            HttpMessageNotWritableException {
        OutputStream out = outputMessage.getBody();
        String text = JSON.toJSONString(obj);
        byte[] bytes = text.getBytes("utf-8");
        out.write(bytes);
    }
}
